﻿#region using
using System;
using System.Threading;
using SilverCrmSoap.CrmSdk;

#endregion

namespace SLTimeZoneHelper.CRM2011
{
   public sealed partial class TimeZoneAdapter
   {
      public TimeZoneAdapter(IOrganizationService proxy)
      {
         Proxy = proxy;
      }

      public IOrganizationService Proxy { get; private set; }
      public event EventHandler<TimeZoneArgs> GetTimeZoneCompleted;

      public void GetTimeZone(int zoneCode)
      {
         Proxy.BeginRetrieveMultiple(TimeZoneQueryHelper.DefaultTimeZoneQuery(zoneCode), GetTimeZoneCompletedInternal, Proxy);
      }

      private void GetTimeZoneCompletedInternal(IAsyncResult result)
      {
         TimeZoneArgs args = new TimeZoneArgs();
         try
         {
            EntityCollection resp = Proxy.EndRetrieveMultiple(result);
            args.TimeZone = TimeZoneQueryHelper.ParseDefaultTimeZoneResponse(resp);
         }
         catch (Exception e)
         {
            args.Exception = e;
         }
         finally
         {
            if (Interlocked.CompareExchange(ref GetTimeZoneCompleted, null, null) != null)
            {
               GetTimeZoneCompleted(this, args);
            }
         }
      }

      public event EventHandler<TimeZonesArgs> GetAllTimeZonesCompleted;

      public void GetAllTimeZones()
      {
         Proxy.BeginRetrieveMultiple(TimeZoneQueryHelper.DefaultTimeZoneQuery(), GetAllTimeZonesCompletedInternal, Proxy);
      }

      private void GetAllTimeZonesCompletedInternal(IAsyncResult result)
      {
         TimeZonesArgs args = new TimeZonesArgs();
         try
         {
            EntityCollection resp = Proxy.EndRetrieveMultiple(result);
            args.TimeZones = TimeZoneQueryHelper.ParseDefaultTimeZonesResponse(resp);

            var it = args.TimeZones;
            string str = Util.Serializer.Serialize(it);
            
         }
         catch (Exception e)
         {
            args.Exception = e;
         }
         finally
         {
            if (Interlocked.CompareExchange(ref GetAllTimeZonesCompleted, null, null) != null)
            {
               GetAllTimeZonesCompleted(this, args);
            }
         }         
      }
   }
}